<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 异步请求
 * @param type $url
 * @param type $post_data
 * @return boolean
 */
function request_by_fsockopen($url, $post_data = array()) {
    $url_array = parse_url($url);
    $hostname = $url_array['host'];
    $port = isset($url_array['port']) ? $url_array['port'] : 80;
    $requestPath = $url_array['path'] . "?" . $url_array['query'];
    $fp = fsockopen($hostname, $port, $errno, $errstr, 10);
    if (!$fp) {
        echo "$errstr ($errno)";
        return false;
    }
    $method = "GET";
    if (!empty($post_data)) {
        $method = "POST";
    }
    $header = "$method $requestPath HTTP/1.1\r\n";
    $header .= "Host: $hostname\r\n";
    if (!empty($post_data)) {
        $_post = strval(NULL);
        foreach ($post_data as $k => $v) {
            $_post[] = $k . "=" . urlencode($v); //必须做url转码以防模拟post提交的数据中有&符而导致post参数键值对紊乱
        }
        $_post = implode('&', $_post);
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; //POST数据
        $header .= "Content-Length: " . strlen($_post) . "\r\n"; //POST数据的长度
        $header .= "Connection: Close\r\n\r\n"; //长连接关闭
        $header .= $_post; //传递POST数据
    } else {
        $header .= "Connection: Close\r\n\r\n"; //长连接关闭
    }
    fwrite($fp, $header);
    //-----------------调试代码区间-----------------
    /* $html = '';
      while (!feof($fp)) {
      $html.=fgets($fp);
      }
      echo $html; */
    //-----------------调试代码区间-----------------
    fclose($fp);
}

/**
 * 格式化输出，方便开发过程中的调试
 * @param type $array
 */
function p($array) {
    dump($array, 1, '<pre>', 0);
}

/**
 * 递归判断：值是否在(多维)数组中
 * @param type $value
 * @param type $array
 * @return boolean
 */
function deep_in_array($value, $array) {
    foreach ($array as $item) {
        if (!is_array($item)) {
            if ($item == $value) {
                return true;
            } else {
                continue;
            }
        }

        if (in_array($value, $item)) {
            return true;
        } else if (deep_in_array($value, $item)) {
            return true;
        }
    }
    return false;
}

/**
 * 头像上传初始化
 * @param string $img
 * @return boolean|string
 */
function img_headimg($img) {
    $upload = new \Think\Upload(); // 实例化上传类    
    $upload->maxSize = 3145728; // 设置附件上传大小    
    $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型    
    $upload->savePath = '/Public/uploads/headimg/'; // 设置附件上传目录    // 上传单个文件
    $upload->saveName = time() . '_' . mt_rand();
    $info = $upload->uploadOne($img);
    if (!$info) {// 上传错误提示错误信息        
        return FALSE;
    } else {// 上传成功 获取上传文件信息         
        $img = $info['savepath'] . $info['savename'];
        return $img;
    }
}

/**
 * 广告上传初始化
 * @param string $img
 * @return boolean|string
 */
function upload_img() {
    $upload = new \Think\Upload(); // 实例化上传类    
    $upload->maxSize = 3145728; // 设置附件上传大小    
    $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型    
    $upload->savePath = '/Public/uploads/adv/'; // 设置附件上传目录    // 上传单个文件
    $upload->saveName = time() . '_' . mt_rand();
    $info = $upload->upload();
    if (!$info) {// 上传错误提示错误信息        
        return FALSE;
    } else {// 上传成功 获取上传文件信息    
        return $info;
    }
}

/**
 * 上传企业logo
 * @param string $img
 * @return boolean|string
 */
function upload_logo($img) {
    $upload = new \Think\Upload(); // 实例化上传类    
    $upload->maxSize = 3145728; // 设置附件上传大小    
    $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型    
    $upload->savePath = '/Public/Besiness/'; // 设置附件上传目录    // 上传单个文件
    $upload->saveName = time() . '_' . mt_rand();
    $info = $upload->uploadOne($img);
    if (!$info) {// 上传错误提示错误信息        
        return FALSE;
    } else {// 上传成功 获取上传文件信息         
        $img = $info['savepath'] . $info['savename'];
        return $img;
    }
}

/**
 * 商家用户密码加密算法
 * @param type $password    密码
 */
function pwdBysha256($password) {
    if (empty($password)) {
        return false;
    } else {
        $salt = substr($password, 2, 2) . substr($password, -4);
        $str = hash_hmac('sha256', $password, $salt); //sha256 加密
        return $str;
    }
}

/**
 * 写入文件
 * @param string $path 图片路径、名称
 */
function writefile() {
    
}

/**
 * 发送短信验证码 - 聚合短信(模板)
 * @param type $action
 * @param type $mobile
 * @param type $code
 */
function sendSmsByTpl($action, $mobile, $code) {
    //http://v.juhe.cn/sms/send?
    //mobile=13698885713&
    //tpl_id=21152&
    //tpl_value=%23code%23%3D654654&
    //key=aabaf3fc2d4faf5895c293e419126942
    if (empty($action) || empty($mobile) || empty($code)) {
        return false;
    } else {
        $conf = C('juhe');
        if (checkMobile($mobile)) {
            if (empty($conf)) {
                $conf = array(
                    'send_url' => 'http://v.juhe.cn/sms/send',
                    'tpl' => array(
                        'regist' => array('tpl_id' => 27273, 'tpl_val' => '#code#'), //注册
                    //'find_pwd' => array('tpl_id' => 21155, 'tpl_val' => '#code#'), //找回密码
                    //'change_pay_pwd' => array('tpl_id' => 21156, 'tpl_val' => '#code#') //变更支付密码
                    ),
                    'key' => 'aabaf3fc2d4faf5895c293e419126942'
                );
            }
            $dos = array_keys($conf['tpl']);
            if (in_array($action, $dos)) {
                $url = $conf['send_url'];
                $param = array(
                    'mobile' => $mobile,
                    'tpl_id' => $conf['tpl'][$action]['tpl_id'],
                    'tpl_value' => $conf['tpl'][$action]['tpl_val'] . '=' . $code,
                    'key' => $conf['key']
                );
                $url .= '?' . http_build_query($param);
                import('Common.Library.Https');
                $http_handle = \Common\Library\Https::doGet($url);
                //$http_handle = '{"reason":"操作成功","result":{"sid":"1000930112935533200","fee":1,"count":1},"error_code":0}';
                if ($http_handle) {
                    $arr = json_decode($http_handle, TRUE);
                    if ($arr['error_code'] == '0') {
                        return true;
                    } else {
                        //todo...错误码特殊处理
                        return FALSE;
                    }
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}

function log_txt($log) {
    $file = APP_PATH . 'Runtime/Logs/' . date('Y-m-d', time()) . '.txt';
    $fp = fopen($file, 'ab+');
    fwrite($fp, '【' . date('Y-m-d H:i:s', time()) . '】');
    fwrite($fp, $log);
    fwrite($fp, "\r\n");
    fclose($fp);
}

/**
 * 验证手机号码格式
 * @param type $mobile
 * @return type
 */
function checkMobile($mobile) {
    $g = '/^1[34578]\d{9}$/';
    return preg_match($g, $mobile);
}

function setpoints($uid, $points, $type, $manage_id = 0) {
    $before_point = M('users')->where('uid = ' . $uid)->getField('points');
    $after_point = $before_point + $points;
    $data = array(
        'uid' => $uid, //会员ID，就你要给那个会员操作积分就传入那个会员的ID
        'points' => $points, //操作的积分数量,正数为加分，负数为减分；
        'type' => $type, //操作理由，简单的积分操作理由；配置文件对应 eg：1=>登录时送*积分
        'created' => time(), //操作时间
        'manage_id' => $manage_id, //操作员ID,如果为0表示系统操作；
        'before_points' => $before_point,
        'after_points' => $after_point
    );
    M('points_list')->add($data);    //写入积分操作明细数据；
    M('users')->where('uid = ' . $uid)->setInc('points', $points);   //更新会员表积分字段；
}

/**
 * 获取openID和access_token 并返回微信用户 个人信息
 * @param type $appid
 * @param type $secret
 * @param type $code
 */
function get_openid($appid, $secret, $code) {
    //获取openID
    $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $get_token_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $res = curl_exec($ch);
    //解析数据
    $json_obj = json_decode($res, true);
    //根据openid和access_token查询用户信息 
    //$access_token = $json_obj['access_token'];
    $openid = $json_obj['openid'];
    //获取access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    $jsoninfo = json_decode($output, true);
    $access_token = $jsoninfo["access_token"];

    //获取用户信息
    $get_user_info_url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $get_user_info_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $res = curl_exec($ch);
    curl_close($ch);
    //结果返回
    return $res;
}

/**
 * 取汉字的第一个字的首字母 
 * @param type $str 
 * @return string|null 
 */
function getFirstCharter($str) {
    
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z'))
        return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284)
        return 'A';
    if ($asc >= -20283 && $asc <= -19776)
        return 'B';
    if ($asc >= -19775 && $asc <= -19219)
        return 'C';
    if ($asc >= -19218 && $asc <= -18711)
        return 'D';
    if ($asc >= -18710 && $asc <= -18527)
        return 'E';
    if ($asc >= -18526 && $asc <= -18240)
        return 'F';
    if ($asc >= -18239 && $asc <= -17923)
        return 'G';
    if ($asc >= -17922 && $asc <= -17418)
        return 'H';
    if ($asc >= -17417 && $asc <= -16475)
        return 'J';
    if ($asc >= -16474 && $asc <= -16213)
        return 'K';
    if ($asc >= -16212 && $asc <= -15641)
        return 'L';
    if ($asc >= -15640 && $asc <= -15166)
        return 'M';
    if ($asc >= -15165 && $asc <= -14923)
        return 'N';
    if ($asc >= -14922 && $asc <= -14915)
        return 'O';
    if ($asc >= -14914 && $asc <= -14631)
        return 'P';
    if ($asc >= -14630 && $asc <= -14150)
        return 'Q';
    if ($asc >= -14149 && $asc <= -14091)
        return 'R';
    if ($asc >= -14090 && $asc <= -13319)
        return 'S';
    if ($asc >= -13318 && $asc <= -12839)
        return 'T';
    if ($asc >= -12838 && $asc <= -12557)
        return 'W';
    if ($asc >= -12556 && $asc <= -11848)
        return 'X';
    if ($asc >= -11847 && $asc <= -11056)
        return 'Y';
    if ($asc >= -11055 && $asc <= -10247)
        return 'Z';
    return null;
}
